﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Reflection;

namespace BbsbWebService.Logging
{
    public class FileLogger : ILogger
    {
        private static readonly object LockObject = new object();
        private static string LogDir
        {
            get
            {
                FileInfo file = new FileInfo(Assembly.GetExecutingAssembly().Location);
                return Path.Combine(file.Directory.FullName, "BbsbWebServiceLog");
            }
        }
        
        #region ILogger Members

        public void LogMessage(string message, params object[] stringFormatArgs)
        {
            // Perform logging in a separate thread so as not to impact service call duration
            ThreadPool.QueueUserWorkItem(o =>
            {
                lock (LockObject)
                {
                    FileInfo logFile = new FileInfo(Path.Combine(LogDir, AppSettings.Instance.ApplicationStartTime.ToString("yyyyMMddHHmm") + ".txt"));
                    if (!Directory.Exists(logFile.Directory.FullName))
                    {
                        Directory.CreateDirectory(logFile.Directory.FullName);
                    }

                    StreamWriter logWriter;

                    try
                    {
                        if (File.Exists(logFile.FullName))
                        {
                            logWriter = new StreamWriter(new FileStream(logFile.FullName, FileMode.Append, FileAccess.Write, FileShare.None));
                        }
                        else
                        {
                            logWriter = new StreamWriter(new FileStream(logFile.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None));
                        }
                    }
                    catch
                    {
                        throw new ApplicationException("Log file locked");
                    }

                    logWriter.WriteLine(DateTime.Now.ToString() + ": " + string.Format(message, stringFormatArgs));
                    logWriter.Flush();
                    logWriter.Close();
                }
            });
        }

        public void LogException(Exception ex, string message, params object[] stringFormatArgs)
        {
            LogMessage(message + string.Format("; ERROR: {0}", ex.Message), stringFormatArgs); 
        }

        public void LogListener(string message, params object[] stringFormatArgs)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
